package com.jianan.mis.app.login;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.eclipse.core.runtime.preferences.ConfigurationScope;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.osgi.service.prefs.BackingStoreException;
import org.osgi.service.prefs.Preferences;

import com.jianan.mis.data.domain.User;
import com.jianan.mis.sys.IAppConstants;
import com.jianan.mis.sys.IImageKeys;
import com.jianan.mis.sys.ImageManager;

/**
 * Login dialog, which prompts for the user's account info, and has Login and
 * Cancel buttons.
 */
public class LoginDialog extends Dialog {

	private Combo usernameText;

	private Text passwordText;

	private User user;

	private Map<String, User> savedUsers = new HashMap<String, User>();

	private static final String PASSWORD = "password";

	private static final String SAVED = "saved-connections";

	private static final String LAST_USER = "prefs_last_connection";

	public LoginDialog(Shell parentShell) {
		super(parentShell);
		loadDescriptors();
	}

	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setImage(ImageManager.getImage(IImageKeys.LOGIN));
		newShell.setText("福建建安留学神州移民内部MIS");
	}

	public boolean close() {
		return super.close();
	}

	protected Control createDialogArea(Composite parent) {
		Composite composite = new Composite(parent, SWT.NONE);
		composite.setLayoutData(new GridData());
		GridLayout layout = new GridLayout(2, false);
		composite.setLayout(layout);

		Label accountLabel = new Label(composite, SWT.NONE);
		accountLabel.setText("登陆:");
		accountLabel.setLayoutData(new GridData(GridData.BEGINNING,
				GridData.CENTER, false, false, 2, 1));

		Label usernameLabel = new Label(composite, SWT.NONE);
		usernameLabel.setText("用户ID:");
		usernameLabel.setLayoutData(new GridData(GridData.END, GridData.CENTER,
				false, false));

		usernameText = new Combo(composite, SWT.BORDER);
		GridData gridData = new GridData(GridData.FILL, GridData.FILL, true,
				false);
		gridData.widthHint = convertHeightInCharsToPixels(20);
		usernameText.setLayoutData(gridData);
		usernameText.addListener(SWT.Modify, new Listener() {
			public void handleEvent(Event event) {
				User u = (User) savedUsers.get(usernameText.getText());
				if (u != null) {
					passwordText.setText(u.getPassword());
				}
			}
		});

		Label passwordLabel = new Label(composite, SWT.NONE);
		passwordLabel.setText("密  码:");
		passwordLabel.setLayoutData(new GridData(GridData.END, GridData.CENTER,
				false, false));

		passwordText = new Text(composite, SWT.BORDER | SWT.PASSWORD);
		passwordText.setLayoutData(new GridData(GridData.FILL, GridData.FILL,
				true, false));

		String lastUser = "none";
		if (user != null)
			lastUser = user.getUsername();
		initializeUsers(lastUser);

		return composite;
	}

	protected void createButtonsForButtonBar(Composite parent) {
		Button removeCurrentUser = createButton(parent,
				IDialogConstants.CLIENT_ID, "清除登陆历史", false);
		removeCurrentUser.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				savedUsers.remove(usernameText.getText());
				try {
					Preferences preferences = new ConfigurationScope()
							.getNode(IAppConstants.APPLICATION_ID);
					Preferences connections = preferences.node(SAVED);
					connections.node(user.getUsername()).removeNode();
				} catch (BackingStoreException ex) {
					ex.printStackTrace();
				}
				initializeUsers("");
			}
		});
		createButton(parent, IDialogConstants.OK_ID, "登陆", true);
		createButton(parent, IDialogConstants.CANCEL_ID, "取消", false);
	}

	protected void initializeUsers(String defaultUser) {
		usernameText.removeAll();
		passwordText.setText("");
		for (Iterator it = savedUsers.keySet().iterator(); it.hasNext();)
			usernameText.add((String) it.next());
		int index = Math.max(usernameText.indexOf(defaultUser), 0);
		usernameText.select(index);
	}

	protected void okPressed() {
		if (user.getUsername().equals("")) {
			MessageDialog.openError(getShell(), "非法用户ID", "用户ID不能为空!");
			return;
		}
		super.okPressed();
	}

	protected void buttonPressed(int buttonId) {
		if (buttonId == IDialogConstants.CLIENT_ID) {
			return;
		}
		String username = usernameText.getText();
		String password = passwordText.getText();
		user = new User();
		user.setUsername(username);
		user.setPassword(password);
		savedUsers.put(username, user);

		if (buttonId == IDialogConstants.OK_ID)
			saveDescriptors();
		super.buttonPressed(buttonId);
	}

	public void saveDescriptors() {
		try {
			Preferences preferences = new ConfigurationScope()
					.getNode(IAppConstants.APPLICATION_ID);
			preferences.put(LAST_USER, user.getUsername());
			Preferences connections = preferences.node(SAVED);

			for (Iterator it = savedUsers.keySet().iterator(); it.hasNext();) {
				String name = (String) it.next();
				//User savedUser = (User) savedUsers.get(name);
				Preferences connection = connections.node(name);
				//connection.put(PASSWORD, savedUser.getPassword());
				connection.put(PASSWORD, "");
			}

			preferences.flush();
		} catch (BackingStoreException e) {
			e.printStackTrace();
		}
	}

	private void loadDescriptors() {
		try {
			Preferences preferences = new ConfigurationScope()
					.getNode(IAppConstants.APPLICATION_ID);
			Preferences connections = preferences.node(SAVED);
			String[] userNames = connections.childrenNames();
			for (int i = 0; i < userNames.length; i++) {
				String userName = userNames[i];
				//Preferences node = connections.node(userName);
				User savedUser = new User();
				savedUser.setUsername(userName);
				//savedUser.setPassword(node.get(PASSWORD, ""));
				savedUser.setPassword("");
				savedUsers.put(userName, savedUser);
			}
			user = (User) savedUsers.get(preferences.get(LAST_USER, ""));
		} catch (BackingStoreException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Returns the user details entered by the user, or <code>null</code> if
	 * the dialog was canceled.
	 */
	public User getUser() {
		return user;
	}
}